package com.timothy.android.util;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

/**设计原理：在Toast显示消失之前，再次调用Toast.show()进行接力。*/
public class StopPollingToast {
	/** 用于测试 */
	private Toast toast = null;
	private Context context;
	private Handler handler = null;
	
	private Runnable toastThread = new Runnable() {
		public void run() {
//			toast.setText("Stop Polling");
			toast.show();
			handler.postDelayed(toastThread, 1000);
		}
	};
	
	public StopPollingToast(Context context) {
		this.context = context;
		handler = new Handler(this.context.getMainLooper());
		toast = Toast.makeText(this.context, "Stop Polling", Toast.LENGTH_SHORT);
	}
	public void setText(String text) {
		toast.setText(text);
	}
	public void showToast(final long length) {
		handler.post(toastThread);
		Thread timeThread = new Thread() {
			public void run() {
				try {
					Thread.sleep(length);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				StopPollingToast.this.stopToast();
			}
		};
		timeThread.start();
	}
	public void stopToast() {
		handler.removeCallbacks(toastThread);
		toast.cancel();
	}
}